<template>
	<van-search :value="school_name" shape="round" placeholder="请输入想添加的学校名称" @change="onChangeSchool" />
	<view>
		<view class="pselect">请选择</view>
		<van-cell v-for="(item,index) in schools" :key="index" :clickable="true" @click="toIndex(item)">
			<view slot="title">{{item.name}}</view>
		</van-cell>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onReachBottom,
		onShow
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive
	} from 'vue';
	import {
		getSchoolList,
		getsetSchool

	} from "@/api/index.js"
	const school_name = ref();

	const pageSize = ref(1);

	const keyword = ref('');

	const schools = ref();
	const totalPage = ref()
	//获取学校列表
	const schoolList = async () => {
		try {
			let data = {
				page: pageSize.value,
				keyword: keyword.value
			}
			let res = await getSchoolList(data);
			console.log(res)
			schools.value = res.data
			totalPage.value = res.data.totalPage
		} catch (e) {
			//TODO handle the exception
		}
	}
	//搜索学校
	const onChangeSchool = (e) => {
		keyword.value = e.detail;
		schoolList();
	}

	//跳转首页
	// 跳转首页
	const toIndex = async (item) => {
		// 验证数据有效性
		if (!item || !item.id || !item.name) {
			console.error('学校数据无效:', item);
			uni.showToast({
				title: '学校信息错误',
				icon: 'none'
			});
			return;
		}

		try {
			// 等待API请求完成
			const res = await getsetSchool({
				depId: item.id
			});

			console.log('设置学校响应:', res);

			// 根据返回结果处理
			if (res && res.msg === '200') {
				// 统一设置存储数据
				uni.setStorageSync('school_id', item.id);
				uni.setStorageSync('school_name', item.name);

				// 更新全局数据
				getApp().globalData.school_name = item.name;

				console.log('已保存学校信息:', item.id, item.name);

				//将所返回的楼栋信息和商品信息进行存储到本地
				// 楼栋信息
				uni.setStorageSync('runDepartmentList', res.data.runDepartmentList);




				// 数据保存成功后再跳转
				uni.navigateBack();
			} else {
				// 处理非200响应
				console.error('设置学校失败:', res);
				uni.showToast({
					title: '设置学校失败',
					icon: 'none'
				});
			}
		} catch (error) {
			// 处理请求异常
			console.error('请求异常:', error);
			uni.showToast({
				title: '网络请求失败',
				icon: 'none'
			});
		}
	};
	onReachBottom(() => {
		if ((totalPage.value <= pageSize.value) || schools.value.length === 0) {
			uni.showToast({
				title: '没有更多数据了',
				icon: 'none'
			})
			return
		}
		console.log('3')
		schoolList()
	})

	onShow(() => {
		schoolList();
	})
</script>
<style scoped>
	.pselect {
		background-color: #f5f5f5;
		color: #3c91ff;
		font-size: 36rpx;
		height: 100rpx;
		line-height: 100rpx;
		font-weight: bold;
		padding-left: 50rpx;
	}

	::v-deep .van-cell__title {
		font-size: 32rpx;
		margin: 20rpx 0;
		padding-left: 20rpx;
	}
</style>